package com.jhh.pay.center.search.impl;

import com.jhh.pay.center.search.AbstractMapping;
import com.jhh.pay.center.search.AbstractQuery;
import com.jhh.pay.center.search.IndexRouter;
import com.jhh.pay.center.search.PagedList;
import com.jhh.pay.center.search.mapping.OrderMapping;
import com.jhh.pay.center.search.query.OrderQuery;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author tangxd
 * @Description: TODO
 * @date 2017/12/15
 */
@Service
public class OrderElasticSearcher extends AbstractOrderElasticSearcher<OrderMapping> {
    @Override
    protected String getIdxTypeName() {
        return null;
    }

    @Override
    protected IndexRouter getRouter() {
        return null;
    }

    @Override
    public Map<String, Object> initSetting() {
        return null;
    }

    @Override
    public PagedList<AbstractMapping> search(AbstractQuery query) {
        if (!(query instanceof OrderQuery)) {
            throw new IllegalArgumentException("query parameter fail");
        }
        OrderQuery q = (OrderQuery) query;
        SearchRequestBuilder builder = client.prepareSearch(this.getIdxAlias());
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        if (q.getAppId() != null) {
            queryBuilder.must(QueryBuilders.termQuery("app_id", q.getAppId()));
        }
        if (q.getOrderNo() != null) {
            queryBuilder.must(QueryBuilders.termQuery("order_no", q.getOrderNo()));
        }
        if (q.getPage() <= 0) {
            q.setPage(1);
        }
        builder.setQuery(queryBuilder);
        int offset = (q.getPage() - 1) * q.getSize();
        builder.setFrom(offset).setSize(q.getSize());
        SearchResponse resp;
        resp = builder.execute().actionGet();
        if (resp.status() != RestStatus.OK) {
            return new PagedList<>(new ArrayList<>(), 0, q.getPage(), q.getSize());
        }
        List<AbstractMapping> list = new ArrayList<>();
        SearchHits hits = resp.getHits();
        for (SearchHit hit : hits.getHits()) {
            String source = hit.getSourceAsString();
            OrderMapping m = sourceTransformer().transform(source);
            if (null != m) {
                m.setVersion(hit.getVersion());
                list.add(m);
            }
        }
        return new PagedList<>(list, hits.totalHits, q.getPage(), q.getSize());
    }

}
